package com.weilele.mvvm.utils.activity

import android.app.Activity
import android.content.res.Resources
import android.graphics.Color
import android.os.Build
import android.view.View
import android.view.Window
import android.view.WindowInsetsController
import android.view.WindowManager

/**
 * 状态栏文字颜色，只有白色和黑色
 */
fun Activity.isStatusBarBlackTextColor(isBlackStatusBarTextColor: Boolean) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        window.decorView.windowInsetsController?.apply {
            if (isBlackStatusBarTextColor) {
                setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS)
            } else {
                setSystemBarsAppearance(0, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS)
            }
        }
    } else {
        if (isBlackStatusBarTextColor) {
            //状态栏文字黑色
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            }
        } else {
            //系统默认，状态栏文字白色
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE//白色
        }
    }
}

/**
 * 透明状态栏
 */
fun Activity.transparentStatusBar(isBlackStatusBarTextColor: Boolean = false) {
    window.transparentStatusBar(isBlackStatusBarTextColor)
}

fun Window.transparentStatusBar(isBlackStatusBarTextColor: Boolean = false) {
    addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
    statusBarColor = Color.TRANSPARENT
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        decorView.windowInsetsController?.apply {
            setDecorFitsSystemWindows(false)
            if (isBlackStatusBarTextColor) {
                setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS)
            }
        }
    } else {
        var uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        if (isBlackStatusBarTextColor) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                uiFlags = uiFlags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            }
        } else {
            uiFlags = uiFlags or View.SYSTEM_UI_FLAG_VISIBLE
        }
        clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        decorView.systemUiVisibility = uiFlags
    }
}

/**
 * 获取状态栏高度
 */
fun Resources.getStatusBarHeight(): Int {
    val resourceId = getIdentifier("status_bar_height", "dimen", "android");
    return getDimensionPixelOffset(resourceId)
}

/**
 * 获取导航栏高度
 */
fun Resources.getNavigationBarHeight(): Int {
    val resourceId = getIdentifier("navigation_bar_height", "dimen", "android");
    return getDimensionPixelSize(resourceId)
}
